<template>
  <div>
    <!-- <el-card shadow="never"> -->
    <!-- 添加依赖，选择依赖的作业对话框 -->
    <el-dialog v-if="currentJob != null"
               :visible.sync="jobDependencePickJobDialogVisible"
               width="40%"
               :show-close="true">
      <div slot="title">
        <el-row>
          <el-col :span="16">
            <el-tag>请选择需要依赖的作业</el-tag>
          </el-col>
          <el-col :span="8">
            <el-button circle
                       size="mini"
                       type="success"
                       plain
                       @click="jobDependencePickJobDialogVisible = false">取消</el-button>
            <el-button circle
                       size="mini"
                       type="success"
                       plain
                       @click="handleAddDependenceConfirm()">确定</el-button>
          </el-col>
        </el-row>
      </div>
      <el-tree :data="jobList"
               ref="dependenceJobTree"
               show-checkbox
               :expand-on-click-node="false"
               :check-on-click-node="true"
               :check-strictly="true"
               node-key="id"
               :props="defaultProps">
      </el-tree>
    </el-dialog>

    <!-- 依赖对话框 -->
    <el-dialog v-if="currentJob != null"
               :visible.sync="jobDependenceDialogVisible"
               width="80%"
               :show-close="true">
      <div slot="title">
        <el-row>
          <el-col :span="8">
            <el-tag>{{currentJob.jobName}}</el-tag>
          </el-col>
          <el-col :span="16">
            <el-button circle
                       size="mini"
                       :disabled="checkDisabled()"
                       type="success"
                       plain
                       @click="handleAddDependence()">新增</el-button>
            <el-button :disabled="checkDisabled() || currentJob.editDependence"
                       circle
                       size="mini"
                       type="success"
                       plain
                       @click="handleEditDependence()">修改</el-button>
            <el-button :disabled="checkDisabled() || !currentJob.editDependence"
                       circle
                       size="mini"
                       type="success"
                       plain
                       @click="handleDependencePost()">提交</el-button>
            <el-popconfirm confirmButtonText='确定删除'
                           cancelButtonText='点错了，不要删除'
                           icon="el-icon-info"
                           iconColor="red"
                           title="该操作将直接从系统删除已经选中的依赖配置，确定吗？"
                           @onConfirm="handleDependenceDelete()">
              <el-button circle
                         :disabled="checkDisabled() || multipleDependenceSelection.length == 0 "
                         slot="reference"
                         type="success"
                         plain
                         size="mini">删除</el-button>
            </el-popconfirm>
          </el-col>
        </el-row>
      </div>
      <el-table :data="currentJob.monitorDependencies"
                ret="dependenceTable"
                @selection-change="handleDependenceSelectionChange"
                border
                height="280"
                style="width: 100%">
        <el-table-column v-if="currentJob.editDependence"
                         fixed
                         type="selection"
                         width="40">
        </el-table-column>
        <el-table-column fixed
                         label="依赖作业名称"
                         width="260">
          <!-- prop="dependJobName" -->
          <template slot-scope="{row}">
            {{row.dependJobName}}
          </template>
        </el-table-column>
        <el-table-column prop="dependJobId"
                         align="center"
                         label="依赖作业ID"
                         width="100">
        </el-table-column>
        <el-table-column align="center"
                         label="依赖类型"
                         width="130">
          <template slot-scope="{row}">
            <span v-if="currentJob.editDependence">
              <el-select v-model="row.dependType"
                         style="width:100%;"
                         align="center"
                         size="small">
                <el-option v-for="el_select_item 
                                      in getOptions('depend_type')"
                           :key="el_select_item.value"
                           :label="el_select_item.label"
                           :value="el_select_item.value" />
              </el-select>
            </span>
            <span v-else>
              {{ getDictLabel('depend_type', row.dependType)}}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="dependValue"
                         label="依赖值"
                         align="center"
                         width="130">
          <template slot-scope="{row}">
            <template v-if="currentJob.editDependence">
              <span v-if="row.dependType == '1'">
                <el-select v-model="row.dependValue"
                           style="width:100%;"
                           size="small">
                  <el-option v-for="el_select_item 
                                                 in getOptions('task_status')"
                             :key="el_select_item.value"
                             :label="el_select_item.label"
                             :value="el_select_item.value" />
                </el-select>
              </span>
              <span v-else>
                <el-input size="small"
                          v-model="row.dependValue"></el-input>
              </span>
            </template>
            <template v-else>
              <span v-if="row.dependType == '1'">
                {{getDictLabel('task_status', row.dependValue)}}
              </span>
              <span v-else>{{ row.dependValue }}</span>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="备注"
                         align="left"
                         prop="">
          <template slot-scope="{row}">
            <span v-if="currentJob.editDependence">
              <el-input size="small"
                        v-model="row.remark"></el-input>
            </span>
            <span v-else>
              {{ row.remark }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 执行计划对话框 -->
    <el-dialog v-if="currentJob != null"
               :visible.sync="jobPlanDialogVisible"
               width="80%"
               :show-close="true">
      <div slot="title">
        <el-row>
          <el-col :span="8">
            <el-tag>
              {{currentJob.jobName}}
            </el-tag>
          </el-col>
          <el-col :span="16">
            <el-button v-if="! checkPlanEdit()"
                       circle
                       :disabled="checkDisabled()"
                       size="mini"
                       type="success"
                       plain
                       @click="handleCreatNewPlan()">新增</el-button>
            <el-button v-if="checkPlanEdit()"
                       circle
                       :disabled="checkDisabled()"
                       size="mini"
                       type="success"
                       @click="handleCreatNewPlanCommit()">提交</el-button>

            <el-popconfirm confirmButtonText='确定启用'
                           cancelButtonText='点错了，不要启用'
                           icon="el-icon-info"
                           iconColor="red"
                           :disabled="checkDisabled()"
                           title="启用计划将同时生成该计划相关的任务，确定吗？"
                           @onConfirm="handlePlanEnable()">
              <!-- :disabled="multiplePlanSelection.length == 0 || checkPlanEdit() || currentJob.izEnabled == '0'" -->
              <el-button circle
                         :disabled="checkPlanDisabled('1')"
                         slot="reference"
                         type="success"
                         plain
                         size="mini">启用计划</el-button>
            </el-popconfirm>

            <el-popconfirm confirmButtonText='确定撤消'
                           cancelButtonText='点错了，不要撤消'
                           icon="el-icon-info"
                           iconColor="red"
                           title="撤消计划将同时删除该计划相关的任务，确定吗？"
                           @onConfirm="handlePlanDisable()">
              <el-button circle
                         :disabled="checkPlanDisabled('0')"
                         slot="reference"
                         type="success"
                         plain
                         size="mini">撤消计划</el-button>
            </el-popconfirm>
            <el-popconfirm confirmButtonText='狠心删除'
                           cancelButtonText='点错了，不要删'
                           icon="el-icon-info"
                           iconColor="red"
                           title="确定删除已经选中的计划吗？"
                           @onConfirm="handlePlanDelete()">
              <el-button circle
                         :disabled="checkPlanDeleteDisabled()"
                         slot="reference"
                         type="success"
                         plain
                         size="mini">删除</el-button>
            </el-popconfirm>
          </el-col>
        </el-row>
      </div>
      <el-table :data="currentJob.monitorPlans"
                border
                ref="crontabTable"
                @selection-change="handleSelectionChange"
                height="380"
                style="width: 100%">
        <el-table-column fixed
                         type="selection"
                         width="40">
        </el-table-column>
        <el-table-column fixed
                         label="名称"
                         min-width="200">
          <template slot-scope="{row}">
            <template v-if="row.id == null">
              <el-input v-model="row.name"
                        size="small" />
            </template>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="izEnabled"
                         label="状态"
                         align="center"
                         width="80">
          <template slot-scope="{row}">
            <span>{{ getDictLabel('host_is_enabled', row.izEnabled)}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center"
                         label="动作类型"
                         width="100">
          <!-- <template slot-scope="{row}">
                    <span>{{ getDictLabel('action_type', row.actionType)}}</span>
                  </template> -->
          <template slot-scope="{row}">
            <template v-if="row.id == null">
              <el-select v-model="row.actionType"
                         style="width:100%;"
                         size="small">
                <el-option v-for="el_select_item 
                                                 in getOptions('action_type')"
                           :key="el_select_item.value"
                           :label="el_select_item.label"
                           :value="el_select_item.value" />
              </el-select>
            </template>
            <span v-else>{{ getDictLabel('action_type', row.actionType)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行时长"
                         align="center"
                         width="120">
          <template slot-scope="{row}">
            <template v-if="row.actionType == '2'">
              <el-input v-if="row.id == null"
                        v-model="row.runDuration"
                        size="small" />
              <span v-else>{{row.runDuration}}</span>
            </template>
            <span v-else>N/A</span>
          </template>
        </el-table-column>

        <el-table-column label="月份"
                         align="center"
                         width="120">
          <template slot-scope="{row}">
            <el-input v-if="row.id == null"
                      v-model="row.month"
                      size="small" />
            <span v-else>{{row.month}}</span>
          </template>
        </el-table-column>
        <el-table-column label="星期"
                         align="center"
                         width="120">
          <template slot-scope="{row}">
            <el-input v-if="row.id == null"
                      v-model="row.weekday"
                      size="small" />
            <span v-else>{{row.weekday}}</span>
          </template>
        </el-table-column>
        <el-table-column label="日期"
                         align="center"
                         prop="day"
                         width="120">
          <template slot-scope="{row}">
            <el-input v-if="row.id == null"
                      v-model="row.day"
                      size="small" />
            <span v-else>{{row.day}}</span>
          </template>
        </el-table-column>
        <el-table-column label="小时"
                         align="center"
                         width="120">
          <template slot-scope="{row}">
            <el-input v-if="row.id == null"
                      v-model="row.hour"
                      size="small" />
            <span v-else>{{row.hour}}</span>
          </template>
        </el-table-column>
        <el-table-column label="分钟"
                         align="center"
                         width="120">
          <template slot-scope="{row}">
            <el-input v-if="row.id == null"
                      v-model="row.minute"
                      size="small" />
            <span v-else>{{row.minute}}</span>
          </template>
        </el-table-column>

        <el-table-column label="备注"
                         align="left"
                         width="300">
          <template slot-scope="{row}">
            <el-input v-if="row.id == null"
                      v-model="row.remark"
                      size="small" />
            <span v-else>{{row.remark}}</span>
          </template>
        </el-table-column>

      </el-table>
    </el-dialog>
    <el-table :data="jobList"
              v-loading="listLoading"
              border
              row-key="id"
              :height="jobTableHeight"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="作业名称"
                       fixed
                       width="260">
        <template slot-scope="{row}">
          <i v-if="row.izEnabled == '0'"
             class="el-icon-circle-close"></i>
          {{row.jobName}}
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       fixed
                       align="center"
                       width="160">
        <template slot-scope="{row}">
          <el-tooltip class="item"
                      effect="light"
                      content="执行计划"
                      placement="top-start">
            <el-button size="mini"
                       type="primary"
                       circle
                       @click="handlePlanEdit(row)"
                       icon="el-icon-date">
            </el-button>
          </el-tooltip>
          <el-tooltip class="item"
                      effect="light"
                      content="启动依赖"
                      placement="top-start">
            <el-button size="mini"
                       type="primary"
                       circle
                       icon="el-icon-connection"
                       @click="handleDependenceEdit(row)">
            </el-button>
          </el-tooltip>
          <el-tooltip class="item"
                      effect="light"
                      content="任务操作"
                      placement="top-start">
            <el-button size="mini"
                       type="primary"
                       circle
                       icon="el-icon-s-operation"
                       @click="handleSelect(row)">
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="执行计划"
                       width="400">
        <template slot-scope="{row}">
          <a v-for="item in row.monitorPlans"
             :key="item.id">
            <el-tag v-if="item.izEnabled == '0'"
                    type="info">{{item.name}}</el-tag>
            <el-tag v-else>{{item.name}}</el-tag>
            <el-divider direction="vertical"></el-divider>
          </a>
        </template>
      </el-table-column>
      <el-table-column label="启动依赖"
                       width="400">
        <template slot-scope="{row}">
          <a v-for="item in row.monitorDependencies"
             :key="item.id">
            <el-tag v-if="item.dependType =='0'">{{item.dependJobName}}:{{getDictLabel('depend_type', item.dependType)}}:{{item.dependValue}}</el-tag>
            <el-tag v-else>{{item.dependJobName}}:{{getDictLabel('depend_type', item.dependType)}}:{{getDictLabel('task_status', item.dependValue)}}</el-tag>
            <el-divider direction="vertical"></el-divider>
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="remark"
                       width="480"
                       label="备注">
      </el-table-column>
      <!-- <el-table-column label="操作">
              <template slot-scope="{row}">
                <el-button type="warning"
                           size="small"
                           @click="handleCurrentJobChange(row)">下一步</el-button>
              </template>
            </el-table-column> -->
    </el-table>
    <!-- </el-card> -->
  </div>
</template>
<script>
import { formatDate } from "@/utils/date";
import { hasPermission, getEntries, getLabel } from "@/utils/dict";
import { apiJobList, apiPlanCreate, apiPlanEnable, apiPlanDisable, apiPlanDelete, apiDependenceUpdate, apiDependenceDelete } from "@/api/monitor";


export default {
  name: "SelectJob",
  data() {
    return {
      myMap: null,
      jobPlanDialogVisible: false,
      jobDependencePickJobDialogVisible: false,
      jobDependenceDialogVisible: false,
      active: 0,
      radioOption: '执行计划',
      jobList: [],
      multiplePlanSelection: [],
      multipleDependenceSelection: [],
      currentJob: null,
      listLoading: false,
      conheight: {
        height: ''
      },
      jobTableHeight: 500,
      consoleOn: false,
      textarea: '',
      defaultNewPlan: {
        id: null,
        jobId: null,
        actionType: '0',
        schedulerType: '1',
        actionTime: null,
        izEnabled: '0',
        minute: '60',
        hour: '*',
        day: '*',
        weekday: '*',
        month: '*',
        runDuration: 180,
        name: '默认值,修改我吧',
        remark: '备注, 详细说明调度计划',
      },
      defaultProps: {
        children: 'children',
        label: 'jobName',
      }
    };
  },

  created() {
    this.callJobList();
    window.addEventListener('resize', this.getHeight);
    this.getHeight();
  },


  methods: {
    hasPermission(url) {
      return hasPermission(url)
    },
    getOptions(dictKey) {
      return getEntries(dictKey);
    },
    messageSuccess() {
      this.$message({
        type: 'success',
        message: '提交成功!',
        duration: 3000
      });
    },

    checkPlanDisabled(izEnabled) {
      if (this.checkDisabled()) {
        return true;
      }

      if (this.multiplePlanSelection.length == 0 || this.checkPlanEdit() || this.currentJob.izEnabled == '0') {
        return true;
      }

      let hasEnableCronb = false;
      let idx = this.multiplePlanSelection.findIndex(item => { return item.izEnabled == izEnabled });
      if (idx >= 0) {
        return true;
      }
      return false;
    },

    checkPlanDeleteDisabled() {
      if (this.checkDisabled()) {
        return true;
      }

      if (this.multiplePlanSelection.length == 0 || this.checkPlanEdit()) {
        return true;
      }

      let hasEnableCronb = false;
      let idx = this.multiplePlanSelection.findIndex(item => { return item.izEnabled == '1' });
      if (idx >= 0) {
        return true;
      }
      return false;
    },

    handleDependenceDelete() {
      let deletMyIds = []
      this.multipleDependenceSelection.map(e => {
        let myId = {};
        myId.id = e.id;
        deletMyIds.push(myId);
      });

      this.listLoading = true;
      apiDependenceDelete(deletMyIds)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          deletMyIds.map(e => {
            let idx = this.currentJob.monitorDependencies.findIndex((item) => item.id == e.id);
            this.currentJob.monitorDependencies.splice(idx, 1);
          });
          this.$refs.dependenceTable.clearSelection();
          this.messageSuccess();
          this.listLoading = false;
        });
      this.listLoading = false;
    },

    handleEditDependence() {
      this.$set(this.currentJob, 'editDependence', true);
    },

    handlePlanDelete() {
      let deletMyIds = []
      this.multiplePlanSelection.map(e => {
        let myId = {};
        myId.id = e.id;
        deletMyIds.push(myId);
      });

      this.listLoading = true;
      apiPlanDelete(deletMyIds)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          deletMyIds.map(e => {
            let idx = this.currentJob.monitorPlans.findIndex((item) => item.id == e.id);
            this.currentJob.monitorPlans.splice(idx, 1);
          });
          this.$refs.crontabTable.clearSelection();
          this.messageSuccess();
          this.listLoading = false;
        });
      this.listLoading = false;
    },
    handleDependencePost() {
      this.listLoading = true;
      apiDependenceUpdate(this.currentJob.monitorDependencies)
        .then(response => {
          const data = response.data;
          if (data) {
            this.currentJob.monitorDependencies = data;
            this.$set(this.currentJob, 'editDependence', false);
            this.messageSuccess();
          }
        });
      this.listLoading = false;
    },

    handleSelect(row) {
      this.$emit('newTabPanel', row);
    },


    handleDependenceEdit(row) {
      this.currentJob = row;
      this.jobDependenceDialogVisible = true;
    },

    handlePlanEdit(row) {
      this.currentJob = row;
      this.jobPlanDialogVisible = true;
    },

    getDictLabel(dictKey, dictValue) {
      return getLabel(dictKey, dictValue);
    },

    handleCreatNewPlan() {
      let newPlan = JSON.parse(JSON.stringify(this.defaultNewPlan));
      newPlan.jobId = this.currentJob.id;
      this.currentJob.monitorPlans.push(newPlan);
    },

    handlePlanEnable() {
      let deletMyIds = []
      this.multiplePlanSelection.map(e => {
        let myId = {};
        myId.id = e.id;
        deletMyIds.push(myId);
      });

      this.listLoading = true;
      apiPlanEnable(deletMyIds)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          this.multiplePlanSelection.map(e => {
            e.izEnabled = '1';
          });
          this.messageSuccess();
          this.$refs.crontabTable.clearSelection();
          this.listLoading = false;
        });
      this.listLoading = false;
    },

    handleClick(tab, event) {
      console.log(tab, event);
    },

    handleAddDependence() {
      this.jobDependencePickJobDialogVisible = true;
      this.$set(this.currentJob, 'editDependence', true);
      // this.currentJob.editDependence = true;
      this.$nextTick(function () {
        this.$refs.dependenceJobTree.setCheckedKeys([]);
      });
    },

    handleAddDependenceConfirm() {
      this.jobDependencePickJobDialogVisible = false;
      //要为每个选中的作业添加上默认值 
      this.$refs.dependenceJobTree.getCheckedNodes().map((item) => {
        let newDependence = {};
        newDependence.id = null;
        newDependence.jobId = this.currentJob.id;
        newDependence.dependJobId = item.id;
        newDependence.dependJobName = item.jobName;
        if (item.jobType == '3') {
          //依赖作业是普通作业, 依赖默认为返回码等于0
          newDependence.dependType = '0';
          newDependence.dependValue = '0';
        } else {
          //依赖作业是守护进程作业, 作业组, 依赖默认为运行状态
          newDependence.dependType = '1';
          newDependence.dependValue = '2';
        }
        if (this.currentJob.monitorDependencies == null) {
          this.currentJob.monitorDependencies = []
        }
        this.currentJob.monitorDependencies.push(newDependence);
      });
      //开启编辑, 所有依赖都可编辑
      this.$set(this.currentJob, 'editDependence', true);
    },

    handlePlanDisable() {
      let deletMyIds = []
      this.multiplePlanSelection.map(e => {
        let myId = {};
        myId.id = e.id;
        deletMyIds.push(myId);
      });

      this.listLoading = true;
      apiPlanDisable(deletMyIds)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          this.multiplePlanSelection.map(e => {
            e.izEnabled = '0';
          });
          this.messageSuccess();
          this.$refs.crontabTable.clearSelection();
          this.listLoading = false;
        });
      this.listLoading = false;
    },

    handleCreatNewPlanCommit() {
      let idx = this.currentJob.monitorPlans.length - 1;

      this.listLoading = true;
      apiPlanCreate(this.currentJob.monitorPlans[idx])
        .then(response => {
          const data = response.data;
          if (data) {
            this.currentJob.monitorPlans.splice(idx, 1);
            this.currentJob.monitorPlans.push(data);
            this.messageSuccess();
          }
        });
      this.listLoading = false;
    },

    formatTime(time) {
      if (time == null || time === '') {
        return 'N/A';
      }
      let date = new Date(time);
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    },
    getHeight() {
      //this.myHeight = window.innerHeight - 100;
      this.conheight.height = window.innerHeight - 100 + 'px';
      this.jobTableHeight = window.innerHeight - 165 + 'px';
    },

    checkDisabled() {
      return this.currentJob.izEnabled == '0';
    },

    checkPlanEdit() {
      if (this.currentJob.monitorPlans == null || this.currentJob.monitorPlans.length == 0) {
        return false;
      }

      let idx = this.currentJob.monitorPlans.length - 1;
      if (this.currentJob.monitorPlans[idx].id == null) {
        return true;
      }

      return false;
    },

    handleSelectionChange(val) {
      this.multiplePlanSelection = val;
    },

    handleDependenceSelectionChange(val) {
      this.multipleDependenceSelection = val;
    },

    gotoStep(activeStep) {
      if (activeStep == 0) {
        this.active = 0;
      } else if (activeStep == 1) {
        if (this.currentJob == null) {
          this.$message({
            type: 'warning',
            message: '请先选择你需要操作的作业',
            duration: 3000
          });
          return;
        }
        this.active = 1;
      } else if (activeStep == 2) {
        if (this.currentJob == null) {
          this.$message({
            type: 'warning',
            message: '请先选择你需要操作的作业',
            duration: 3000
          })
          return;
        }
        if (this.currentJob.taskProcesses == null) {
          this.$message({
            type: 'warning',
            message: '谨慎操作, 要先查看作业的任务记录情况',
            duration: 3000
          })
          return;
        }
        this.active = 2;
      }
    },

    callJobList() {
      this.listLoading = true;
      apiJobList()
        .then(response => {
          this.$set(this, 'jobList', []);
          this.$set(this, 'currentJob', null);
          this.listLoading = false;
          const data = response.data;
          console.log(data);
          if (data) {
            // https://vuejs.org/v2/guide/reactivity.html
            this.jobList = data;
            this.listLoading = false;
          }
        });
      this.listLoading = false;
    }

  }
};
</script>

<style>
.c-Button {
  border: none;
  border-radius: 2px;
}

.c-Button--close {
  background-color: red;
}
</style>

<style module>
.button {
  border: none;
  border-radius: 2px;
}

.buttonClose {
  background-color: red;
}
</style>
